#pragma once
//协议定制
#include<string>
std::string Space_Separator=" ";
std::string Newline_Separator="\n";
std::string Encode(const std::string&s)//封装
{
    //"len"\n"100 + 88"\n"
    std::string package=std::to_string(s.size());
    package+=Newline_Separator;
    package+=s;
    package+=Newline_Separator;
    return package;

}
bool Decode( std::string&package,std::string*content)//解包
{
    ssize_t pos=s.find(Newline_Separator);
    if(pos==std::string::npos)return false;
    std::string len_str=s.substr(0,pos);
    int len=std::stoi(len_str);
    std::string str=s.substr(pos+1,len);
    int total_len=len+str.size()+2;
    if(s.size()<total_len)return false;
    *content=str;
    package.erase(0,total_len);//解包一个删除一个报文
    return true;
}
class Request
{
    public:
    Request()
    {

    }
    Request(int x,int y,char c)
    :x_(x),y_(y),op_(c)
    {

    }
    bool Serialize(std::string*out) //"x op y"
    {
        std::string s=std::to_string(x_);
        s+=Space_Separator;
        s+=op_;
        s+=Space_Separator;
        s+=std::to_string(y_);
        *out=s;
        return true;
    }

    //"len"\n"100 + 8"\nxxxxxxxxxxxx

    bool Deserialize(const std::string&content)// string,"100 + 3" ->  struct
    {
       ssize_t left_pos= content.find(Space_Separator);
       if(left_pos==std::string::npos)return false;
        std::string left_part=content.substr(0,left_pos);
        ssize_t right_pos=content.rfind(Space_Separator);
        if(right_pos==std::string::npos)return false;
        std::string right_part=content.substr(right_pos+1);
        if(left_pos+2!=right_pos)return false;
        x_=std::stoi(left_part);
        y_=std::stoi(right_part);
        op_=content[left_pos+1];
        return true;
    }
    public:
    int x_;
    int y_;
    char op_;
};

class Response
{
    public:
    Response()
    {

    }
    Response(int result,int code)
    :result_(result),code_(code)
    {

    }
    bool Serialize(std::string*out) //struct -> string, "result code"
    {
        std::string s=std::to_string(result_);
        s+=Space_Separator;
        s+=std::to_string(code_);
        *out=s;
    }
    bool Deserialize(const std::string&content)// string,"result code" ->  struct
    {
      ssize_t pos=  content.find(Space_Separator);
      if(pos==std::string::npos)return false;
      std::string left_part=content.substr(0,pos);
      std::string right_part=content.substr(pos+1);
      result_=std::stoi(left_part);
      code_=std::stoi(right_part);
      return true;
    }

    public:
    int result_;
    int code_;

};